package com.jycode.commons.genericdao.finder.impl;

import java.lang.reflect.Method;

import org.springframework.stereotype.Service;

import com.jycode.commons.genericdao.finder.FinderNamingStrategy;


/**
 * Looks up Hibernate named queries based on the simple name of the invoced
 * class and the method name of the invocation
 */
@Service
public class ExtendedFinderNamingStrategy implements FinderNamingStrategy
{
    // Always look for queries that start with findBy (even if method is iterateBy.. or scrollBy...)
    @SuppressWarnings("unchecked")
	public String queryNameFromMethod(Class findTargetType, Method finderMethod)
    {
        String methodName = finderMethod.getName();
        String methodPart = methodName;
        if(methodName.startsWith("findBy")) {
            // No-op
        }
        else if(methodName.startsWith("do")) {
        	int l = "do".length();
            methodPart = methodName.substring(l, l+1).toLowerCase() + methodName.substring(l+1);
        }
        else if(methodName.startsWith("listBy")) {
            methodPart = "listBy" + methodName.substring("listBy".length());
        }
        else if(methodName.startsWith("iterateBy")) {
            methodPart = "listBy" + methodName.substring("iterateBy".length());
        }
        else if(methodName.startsWith("scrollBy")) {
            methodPart = "findBy" + methodName.substring("scrollBy".length());
        }
        return findTargetType.getSimpleName() + "." + methodPart;
    }
}
